package com.hxc.shop.db;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.hxc.shop.mapper.Mysql"}, sqlSessionFactoryRef = "SqlSessionFactoryMysqlDb")
public class DbMySqlDbConfig {
    @Autowired
    private MybatisInterceptor mybatisInterceptor;

    @Resource
    @Qualifier("dsMysqlDb")
    private DataSource dsMysqlDb;

    /**
     * 创建sqlsessionfactory
     */
    @Bean(name = {"SqlSessionFactoryMysqlDb"})
    @Primary
    public SqlSessionFactory sqlSessionFactoryMysqlDb() throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dsMysqlDb);
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:*.xml");
        sessionFactoryBean.setMapperLocations(resources);
        sessionFactoryBean.setPlugins(new Interceptor[]{mybatisInterceptor});
        return sessionFactoryBean.getObject();
    }

    @Bean(name = {"dbMysqlDbTransactionManager"})
    @Primary
    public DataSourceTransactionManager dbMysqlDbTransactionManager(@Qualifier("dsMysqlDb") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    @Primary
    public SqlSessionTemplate dbMysqlDbSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryMysqlDb());
    }
}
